<template>
  <div class="swiper-carousel" :class="containerClass">
    <div class="carousel-track" ref="track">
      <div
        v-for="(item, index) in extendedItems"
        :key="`${item.originalIndex}-${index}`"
        :class="['carousel-item', getItemClass(index)]"
        :style="getItemStyle(index)"
        @click="handleItemClick(item.originalIndex)"
      >
        <div class="item-content">
          <slot
            name="item"
            :item="item"
            :index="item.originalIndex"
            :is-active="item.originalIndex === currentIndex"
            :on-click="() => handleItemClick(item.originalIndex)"
          >
            <!-- 默认内容：如果没有传入插槽，则使用默认的 BeforeAfterSlider -->
            <BeforeAfterSlider
              :before-image="item.beforeImage"
              :after-image="item.afterImage"
              width="100%"
              height="100%"
              :show-animation="active && item.originalIndex === currentIndex"
              :animation-duration="2.6"
              :show-tag="true"
              tag-text="效果展示"
              border-radius="16px"
              @itemClick="() => handleItemClick(item.originalIndex)"
            />
          </slot>
        </div>
      </div>
      <!-- 只有多项时才显示指示器 -->
      <div v-if="showCarouselControls" class="carousel-indicators">
        <div
          v-for="(_, index) in items"
          :key="index"
          :class="['indicator', { active: index === currentIndex }]"
          @click.stop="goToSlide(index)"
        ></div>
      </div>
    </div>
  </div>
</template>

<script>
import BeforeAfterSlider from '../BeforeAfterSlider.vue'
import BaseCarousel from './BaseCarousel.js'

export default {
  name: 'SwiperCarousel',
  components: {
    BeforeAfterSlider
  },
  props: {
    // 是否激活（用于扇形轮播内嵌的情况）
    active: {
      type: Boolean,
      default: true
    }
  },
  mixins: [BaseCarousel],

  data() {
    return {
      actualIndex: 1, // 实际显示的索引（从1开始，因为索引0是克隆的最后一个元素）
      isTransitioning: false
    }
  },

  computed: {
    // 创建扩展的items数组，包含首尾克隆元素
    extendedItems() {
      if (!this.items || this.items.length === 0) return []

      const extended = []
      const len = this.items.length

      // 添加最后一个元素的克隆（在开头）
      extended.push({
        ...this.items[len - 1],
        originalIndex: len - 1,
        isClone: true
      })

      // 添加原始元素
      this.items.forEach((item, index) => {
        extended.push({
          ...item,
          originalIndex: index,
          isClone: false
        })
      })

      // 添加第一个元素的克隆（在末尾）
      extended.push({
        ...this.items[0],
        originalIndex: 0,
        isClone: true
      })

      return extended
    }
  },

  methods: {
    getItemClass(index) {
      return index === this.actualIndex ? 'swiper-active' : 'swiper-item'
    },

    getItemStyle(index) {
      // 无缝循环轮播的位置计算
      const offset = index - this.actualIndex
      const translateX = offset * 100

      // 为非当前项添加轻微的透明度变化，使切换更平滑
      const opacity = index === this.actualIndex ? 1 : 0.95

      return {
        transform: `translateX(${translateX}%)`,
        opacity,
        zIndex: index === this.actualIndex ? 2 : 1,
        display: 'block',
        transition: this.isTransitioning ? 'transform 0.6s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.6s cubic-bezier(0.4, 0, 0.2, 1)' : 'none'
      }
    },

    // 重写goToSlide方法来支持无缝循环
    goToSlide(targetIndex) {
      if (this.isAnimating || targetIndex === this.currentIndex || !this.items.length) return

      this.isAnimating = true
      this.isTransitioning = true

      // 计算目标的实际索引（+1是因为第一个是克隆元素）
      const targetActualIndex = targetIndex + 1

      this.actualIndex = targetActualIndex
      this.currentIndex = targetIndex
      this.$emit('slideChange', targetIndex)

      setTimeout(() => {
        this.isAnimating = false
        this.isTransitioning = false
      }, 600)
    },

    // 重写nextSlide方法
    nextSlide() {
      if (this.isAnimating || !this.items.length) return

      this.isAnimating = true
      this.isTransitioning = true

      const nextActualIndex = this.actualIndex + 1
      const nextCurrentIndex = (this.currentIndex + 1) % this.items.length

      this.actualIndex = nextActualIndex
      this.currentIndex = nextCurrentIndex
      this.$emit('slideChange', nextCurrentIndex)

      // 检查是否需要重置位置（到达克隆元素）
      setTimeout(() => {
        if (this.actualIndex === this.extendedItems.length - 1) {
          // 到达了最后一个克隆元素，重置到真正的第一个元素
          this.isTransitioning = false
          this.actualIndex = 1
          // 不更新currentIndex，因为它已经是正确的
        }
        this.isAnimating = false
        this.isTransitioning = false
      }, 600)
    },

    // 重写previousSlide方法
    previousSlide() {
      if (this.isAnimating || !this.items.length) return

      this.isAnimating = true
      this.isTransitioning = true

      const prevActualIndex = this.actualIndex - 1
      const prevCurrentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length

      this.actualIndex = prevActualIndex
      this.currentIndex = prevCurrentIndex
      this.$emit('slideChange', prevCurrentIndex)

      // 检查是否需要重置位置（到达克隆元素）
      setTimeout(() => {
        if (this.actualIndex === 0) {
          // 到达了第一个克隆元素，重置到真正的最后一个元素
          this.isTransitioning = false
          this.actualIndex = this.items.length
          // 不更新currentIndex，因为它已经是正确的
        }
        this.isAnimating = false
        this.isTransitioning = false
      }, 600)
    }
  },

  watch: {
    items: {
      handler() {
        // 当items变化时，重置到第一个真实元素
        this.actualIndex = 1
        this.currentIndex = 0
      },
      immediate: true
    }
  },

  mounted() {
    // 初始化位置
    this.actualIndex = 1
    this.currentIndex = 0
  }
}
</script>

<style scoped>
.swiper-carousel {
  position: relative;
  height: 100%;
  width: 100%;
}

.carousel-track {
  position: relative;
  width: 200px;
  height: 280px;
  margin: 0 auto;
  overflow: hidden;
  border-radius: 16px;
}

.carousel-item {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  /* transition由JavaScript动态控制 */
  cursor: pointer;
}

.item-content {
  width: 100%;
  height: 100%;
  border-radius: 16px;
  overflow: hidden;
  position: relative;
  border: 2px solid transparent;
  transition: border-color 0.3s ease;
  background: linear-gradient(145deg, rgba(255, 255, 255, 0.1), transparent);
}

.carousel-item.swiper-active .item-content {
  /* box-shadow: 
    0 10px 40px rgba(255, 107, 53, 0.3),
    0 4px 12px rgba(0, 0, 0, 0.2); */
}

.carousel-indicators {
  display: flex;
  justify-content: center;
  gap: 8px;
  position: absolute;
  bottom: 8px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
}

.indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.4);
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.indicator.active {
  background: #FF6B35;
  width: 10px;
  height: 10px;
  box-shadow: 0 0 8px rgba(255, 107, 53, 0.6);
  border-color: #FF6B35;
  animation: pulse 2s infinite;
}

.indicator:hover {
  background: rgba(255, 255, 255, 0.6);
  transform: scale(1.1);
}

@keyframes pulse {
  0%, 100% { 
    opacity: 1; 
    transform: scale(1); 
  }
  50% { 
    opacity: 0.7; 
    transform: scale(1.1); 
  }
}
</style>